//
//  b.m
//  ClockIn v2
//
//  Created by Tomy on 12/11/2020.
//

#import "ClockInViewController.h"
#import "Utility.h"
#import "Masonry.h"
#import "CollectionCell.h"
#import "FindViewController.h"

@interface ClockInViewController () <UITextFieldDelegate> {
    NSInteger numberPics;
    NSMutableArray *inputs;
}

@end

@implementation ClockInViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    numberPics = 5;
    inputs = [NSMutableArray new];
    
    self.navigationItem.title = @"添加打卡";

    [Utility addGradientLayerToView:self.view];
    
    NSArray *inputList = @[@"日期", @"地点", @"景点名称", @"心得"];
    NSMutableArray *containers = [NSMutableArray new];
    for (int i = 0; i < inputList.count; ++i) {
        // 包括标签和文本框
        UIView *container = [UIView new];
        [self.view addSubview:container];
        CGFloat containerWidth = 0.9 * self.view.bounds.size.width;
        CGFloat containerHeight = i < 3? 35: 100;
        [container mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(containerWidth);
            make.height.mas_equalTo(containerHeight);
            if (i == 0) {
                make.top.equalTo(self.view).offset([Utility getTopBarWidth] + 25);
            }
            else {
                make.top.equalTo(((UIView*)containers[i - 1]).mas_bottom).offset(10);
            }
            make.centerX.equalTo(self.view.mas_centerX);
        }];
        [containers addObject:container];
        
        // 标签
        UILabel *inputLabel = [UILabel new];
        inputLabel.text = inputList[i];
        [container addSubview:inputLabel];
        [inputLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(0.2 * containerWidth);
            make.top.equalTo(container).offset(5);
            make.left.equalTo(container).offset(5);
        }];
        
        // 文本框
        UIView *input;
        if (i != 3) {
            // 显示一行
            input = [UITextField new];
            ((UITextField*)input).delegate = self;
        }
        else {
            // 显示多行
            input = [UITextView new];
            input.backgroundColor = [UIColor clearColor];
        }
        input.layer.borderColor = [UIColor grayColor].CGColor;
        input.layer.borderWidth = 1.0f;
        [container addSubview:input];
        [input mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(0.7 * containerWidth);
            make.height.mas_equalTo(containerHeight);
            make.right.equalTo(container).offset(-5);
        }];
        
        [inputs addObject:input];
    }
    
    // 配图
    UILabel *picsLabel = [UILabel new];
    picsLabel.text = @"配图";
    [self.view addSubview:picsLabel];
    [picsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(((UIView*)containers[3]).mas_bottom).offset(20);
        make.left.equalTo(containers[3]).offset(5);
    }];
    
    // 配图布局
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 10;
    layout.minimumLineSpacing = 10;
    CGFloat itemW = 90;
    layout.itemSize = CGSizeMake(itemW, itemW);
    layout.sectionInset = UIEdgeInsetsMake(5, 5 ,5, 5);
    layout.sectionFootersPinToVisibleBounds = YES;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    UICollectionView *collection = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    collection.backgroundColor = [UIColor whiteColor];
    collection.showsVerticalScrollIndicator = NO;
    collection.scrollEnabled = YES;
    collection.delegate = self;
    collection.dataSource = self;
    [collection registerClass:[CollectionCell class] forCellWithReuseIdentifier:@"collectioncell"];
    collection.backgroundColor = [UIColor clearColor];
    [self.view addSubview:collection];
    [collection mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(picsLabel);
        make.left.equalTo(picsLabel.mas_right).offset(20);
        make.right.equalTo(self.view).offset(-10);
        make.bottom.equalTo(self.view).offset(-self.tabBarController.tabBar.frame.size.height - 20);
    }];
    
    // 发布按钮
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    [btn setTitle:@"发布" forState:UIControlStateNormal];
    btn.backgroundColor = [UIColor whiteColor];
    [btn addTarget:self action:@selector(publishNew) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(60);
        make.right.equalTo(self.view).offset(-20);
        make.bottom.equalTo(self.view).offset(-self.tabBarController.tabBar.frame.size.height - 20);
    }];
    
    // 轻触外部释放键盘
    UIGestureRecognizer *tapper = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    tapper.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapper];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return numberPics + 1;
}

- (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuse = @"collectioncell";
    CollectionCell * cell  = [collectionView dequeueReusableCellWithReuseIdentifier:reuse forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[CollectionCell alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    }
    NSString *hint;
    if (indexPath.item < numberPics) {
        hint = [NSString stringWithFormat:@"图片"];
        
    }
    else {
        hint = @"+";
    }
    [cell setupWithHint:hint];
    cell.backgroundColor = [UIColor whiteColor];
    return cell;
}

- (void)publishNew {
    NSString *date = ((UITextField*)[inputs objectAtIndex:0]).text;
    NSString *place = ((UITextField*)[inputs objectAtIndex:1]).text;
    NSString *interest = ((UITextField*)[inputs objectAtIndex:2]).text;
    NSString *experience = ((UITextView*)[inputs objectAtIndex:3]).text;
    
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"发布成功" preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alert animated:YES completion:nil];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [alert dismissViewControllerAnimated:YES completion:nil];
        // 转到发现页面
        UINavigationController *nav1 = self.tabBarController.viewControllers[0];
        FindViewController *fvc = (FindViewController*)nav1.topViewController;
        [fvc addNewMarkWithDate:date place:place interest:interest experience:experience];
        [self.tabBarController setSelectedIndex:0];
        
        // 重置文本框内容
        for (int i = 0; i < 3; ++i) {
            ((UITextField*)[self->inputs objectAtIndex:i]).text = @"";
        }
        ((UITextView*)[self->inputs objectAtIndex:3]).text = @"";
    });
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (void)handleSingleTap:(UITapGestureRecognizer *)sender {
    [self.view endEditing:YES];
}


@end

